package com.wohuijituan.whcsmerchant.activity;

import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.TimePicker;


import com.wohuijituan.whcsmerchant.R;
import com.wohuijituan.whcsmerchant.bean.IsSuccessBean;
import com.wohuijituan.whcsmerchant.bean.ShopDetailBean;
import com.wohuijituan.whcsmerchant.callback.IsSuccessCallBack;
import com.wohuijituan.whcsmerchant.url.ParamsKey;
import com.wohuijituan.whcsmerchant.url.Urls;
import com.wohuijituan.whcsmerchant.utils.ExtraName;
import com.wohuijituan.whcsmerchant.utils.LogUtils;
import com.wohuijituan.whcsmerchant.utils.MyOkHttpUtils;
import com.wohuijituan.whcsmerchant.utils.MyRequestParams;

import okhttp3.Call;

/**
 * 说明：
 * 作者：朱世元
 * 时间： 2016/8/25 10:35
 * 版本：V1.0
 * 修改历史：
 */
public class ShopDetailActivity extends MyBaseActivity implements View.OnClickListener,TimePickerDialog.OnTimeSetListener{
    private TextView tvShopName;
    private TextView tvContactInfo;
    private TextView tvOpenHours;
    private TextView tvAlterOpen;
    private TextView tvCloseHours;
    private TextView tvAlterClose;
    private TextView tvDeliverRange;
    private TextView tvAlterDeliverRange;
    private TextView tvDeliverFee;
    private TextView tvAlterDeliverFee;
    private TextView tvStartingFee;
    private TextView tvAlterStartingFee;
    private ImageButton titleGoBack;
    private TextView titleName;
    private TextView titleAction;


    private void assignViews() {
        tvShopName = (TextView) findViewById(R.id.tv_shop_name);
        tvContactInfo = (TextView) findViewById(R.id.tv_contact_info);
        tvOpenHours = (TextView) findViewById(R.id.tv_open_hours);
        tvAlterOpen = (TextView) findViewById(R.id.tv_alter_open);
        tvCloseHours = (TextView) findViewById(R.id.tv_close_hours);
        tvAlterClose = (TextView) findViewById(R.id.tv_alter_close);
        tvDeliverRange = (TextView) findViewById(R.id.tv_deliver_range);
        tvAlterDeliverRange = (TextView) findViewById(R.id.tv_alter_deliver_range);
        tvDeliverFee = (TextView) findViewById(R.id.tv_deliver_fee);
        tvAlterDeliverFee = (TextView) findViewById(R.id.tv_alter_deliver_fee);
        tvStartingFee = (TextView) findViewById(R.id.tv_starting_fee);
        tvAlterStartingFee = (TextView) findViewById(R.id.tv_alter_starting_fee);
        titleGoBack = (ImageButton) findViewById(R.id.title_go_back);
        titleName = (TextView) findViewById(R.id.title_name);
        titleAction = (TextView) findViewById(R.id.title_tv_action);
        titleAction.setText(R.string.confirm);
        titleName.setText(R.string.shop_detail);
    }
    public static final String TAG = "ShopDetailActivity";
    private TimePickerDialog timePicker;//选择时间段的弹窗
    private boolean isOpenTime = true;//判断选择的时间是开门时间还是关门时间
    private static final String DELIVER_RANGE = "配送范围";
    private static final String DELIVER_FEE = "配送费";
    private static final String STARTING_FEE = "起送费";
    private MyOkHttpUtils myOkHttpUtils;
    private MyRequestParams params;
    private static final int ShopDetailEdit_OK = 9712;

    private boolean isOpen = true;
    private int beginHours = 8;
    private int beginMinute = 0;
    private int endHours = 18;
    private int endMinute = 0;
    private int businessRang = 1000;
    private double freight = 5;
    private double minMoney =  20;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_detail);
        assignViews();
        initDate();
        initView();
        initListener();
    }
    private void initView() {
        titleGoBack.setVisibility(View.VISIBLE);
        titleAction.setVisibility(View.VISIBLE);
//        tvContactInfo.setText(shopDetail.getSI_WarnedPhone());
        tvOpenHours.setText(String.format("%02d:%02d", beginHours, beginMinute));
        tvCloseHours.setText(String.format("%02d:%02d", endHours, endMinute));
        tvDeliverRange.setText(businessRang + "m");
        tvDeliverFee.setText("￥" + freight);
        tvStartingFee.setText("￥" + minMoney);
    }
    private void initDate() {
        myOkHttpUtils = new MyOkHttpUtils();
        params = new MyRequestParams();
        Intent intent = getIntent();
        ShopDetailBean.DataEntity shopDetail =
                (ShopDetailBean.DataEntity) intent.getSerializableExtra(ExtraName.SHOP_DETAIL);
        if (shopDetail!=null){//把传入的属性赋值给当前类中的参数
            isOpen = shopDetail.isS_IsBusiness();
            beginHours = shopDetail.getS_Business_BeginHours();
            beginMinute = shopDetail.getS_Business_BeginMin();
            endHours = shopDetail.getS_Business_EndHours();
            endMinute = shopDetail.getS_Business_EndMin();
            businessRang = shopDetail.getS_BusinessRange();
            freight = shopDetail.getS_Freight();
            minMoney = shopDetail.getS_MinMoney();
            tvShopName.setText(shopDetail.getS_Name());
            tvContactInfo.setText(shopDetail.getSI_WarnedPhone());
        }
    }
    private void initListener() {
        tvAlterClose.setOnClickListener(this);
        tvAlterDeliverFee.setOnClickListener(this);
        tvAlterDeliverRange.setOnClickListener(this);
        tvAlterOpen.setOnClickListener(this);
        tvAlterStartingFee.setOnClickListener(this);
        titleAction.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_alter_open:// 开业时间设置
                selectTime(true);
                break;
            case R.id.tv_alter_close:// 关门时间
                selectTime(false);
                break;
            case R.id.tv_alter_deliver_range://T 配送范围
                showAlterDialog(DELIVER_RANGE);
                break;
            case R.id.tv_alter_deliver_fee:// 配送费用
                showAlterDialog(DELIVER_FEE);
                break;
            case R.id.tv_alter_starting_fee:// 起送价格
                showAlterDialog(STARTING_FEE);
                break;
            case R.id.title_tv_action://提交修改请求
                shopDetailEditRequest();
                break;
        }
    }

    /**
     * 弹出一个dialog让用户修改信息
     * @param title
     */
    private void showAlterDialog(final String title){
        final EditText et = new EditText(this);
        et.setPadding(20,0,20,0);
        et.setSingleLine(true);
        new AlertDialog.Builder(this).setTitle(title)
                .setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String input = et.getText().toString();
                        if (input.equals("")) {
                            showToast(ShopDetailActivity.this,"输入不能为空");
                        } else {
                            changeContent(title,input);
                        }
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 改变设置内容
     * @param tag 所要修改的地方
     * @param content 所要修改的内容
     */
    private void changeContent(String tag,String content){
        if(tag == DELIVER_RANGE){
            tvDeliverRange.setText(content+"m");
            businessRang = Integer.parseInt(content);
        }else if (tag == DELIVER_FEE){
            tvDeliverFee.setText("￥"+content);
            freight = Double.parseDouble(content);
        }else if (tag == STARTING_FEE){
            tvStartingFee.setText("￥"+content);
            minMoney = Double.parseDouble(content);
        }
    }
    /**
     * 弹出弹框选择时间
     * @param isOpenTime 为true时选择开门时间,否则为关门时间
     */
    private void selectTime(boolean isOpenTime){
        timePicker = new TimePickerDialog(this,this,12,00,true);
        this.isOpenTime = isOpenTime;
        if (isOpenTime){
            timePicker.setTitle("选择开门时间");
        }else {
            timePicker.setTitle("选择关门时间");
        }
        timePicker.show();
    }
    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        if (isOpenTime){
            tvOpenHours.setText(String.format("%02d:%02d", hourOfDay, minute));
            beginHours = hourOfDay;
            beginMinute = minute;
        }else {
            tvCloseHours.setText(String.format("%02d:%02d", hourOfDay, minute));
            endHours = hourOfDay;
            endMinute = minute;
        }
    }

    /**
     * 修改店铺信息
     */
    private void shopDetailEditRequest(){
        showDialog(ctx);
        String strUrl = Urls.ShopDetailEdit;
        params.addStringRequest(ParamsKey.UserKey,myApplication.getUserKey());
        params.addStringRequest(ParamsKey.ShopDetailEdit_BeginHours,beginHours+"");
        params.addStringRequest(ParamsKey.ShopDetailEdit_BeginMin,beginMinute+"");
        params.addStringRequest(ParamsKey.ShopDetailEdit_IsBusiness,isOpen+"");
        params.addStringRequest(ParamsKey.ShopDetailEdit_EndHours,endHours+"");
        params.addStringRequest(ParamsKey.ShopDetailEdit_EndMin,endMinute+"");
        params.addStringRequest(ParamsKey.ShopDetailEdit_Range,businessRang+"");
        params.addStringRequest(ParamsKey.ShopDetailEdit_Freight,freight+"");
        params.addStringRequest(ParamsKey.ShopDetailEdit_MinMoney,minMoney+"");
        myOkHttpUtils.postRequest(strUrl, params, new IsSuccessCallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                dismissDialog();
                showToast(ctx, "网络出错,请检查网络是否连接!");
                LogUtils.e(TAG, e.getMessage());
            }

            @Override
            public void onResponse(IsSuccessBean response, int id) {
                if (response.getState()==1){
                    if (response.getData().isIsSuccess()){
                        Message msg = new Message();
                        msg.what = ShopDetailEdit_OK;
                        msg.obj = response;
                        handler.sendMessage(msg);
                    }else {
                        showToast(ctx, response.getMsg());
                        dismissDialog();
                    }
                }else {
                    showToast(ctx, response.getMsg());
                    dismissDialog();
                }
            }
        });
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case ShopDetailEdit_OK:
                    // TODO: 2016/10/9 店铺信息修改成功处理
                    dismissDialog();
                    ShopDetailActivity.this.setResult(RESULT_OK);
                    finish();
                    break;
            }
        }
    };
}
